package com.demo.webfluxdemo.controller;

import com.demo.webfluxdemo.domain.User;
import com.demo.webfluxdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * @author: lipan
 * @date: 2021/9/22 21:26
 */
//@RestController
//@RequestMapping("/user")
public class UserController {


    @Autowired
    UserRepository userRepository;

    @RequestMapping("/findAll")
    public Flux<User> findAll(){
        return userRepository.findAll();
    }

    @RequestMapping(value = "flow",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> findAllBySSE(){
        return userRepository.findAll();
    }


    @RequestMapping(method = RequestMethod.POST,value = "/save")
    public Mono<User> save(@RequestBody User user){

        return  userRepository.save(user);
    }

    @DeleteMapping("delete/{id}")
    public Mono<ResponseEntity> deleteUser(@PathVariable String id){

      return    this.userRepository.
                 findById(id).flatMap(user ->this.userRepository.delete(user).then(Mono.just(new ResponseEntity("删除成功", HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity("找不id为:"+id+"的user数据",HttpStatus.BAD_REQUEST));
    }


    @PutMapping("update/{id}")
    public Mono<ResponseEntity> updateUser(@PathVariable String id,@RequestBody User user){
        return    this.userRepository.
                findById(id).flatMap(u ->{
                     u.setId(id);
                     u.setAge(user.getAge());
                     u.setName(user.getName());
                return  this.userRepository.save(u).then(Mono.just(new ResponseEntity("更新成功", HttpStatus.OK)));
        }).defaultIfEmpty(new ResponseEntity("更新失败:不存在id为"+id+"的user数据",HttpStatus.BAD_REQUEST));
    }

}
